package com.moleq.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.DecimalFormat;

public class FileUtil {

	private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;

	/**
	 * Get file size
	 * @param file
	 * @return file size
	 * @throws Exception
	 */
	public static long getFileSize(File f) throws Exception {// 閸欐牕绶遍弬鍥︽婢堆冪毈
		long s = 0;
		if (f.exists()) {
			FileInputStream fis = null;
			fis = new FileInputStream(f);
			s = fis.available();
		} else {
			f.createNewFile();
			System.out.println("閺傚洣娆㈡稉宥呯摠閸︼拷");
		}
		return s;
	}

	// 闁帒缍�
	/**
	 * Get a file size or file size in folder 
	 * @param file
	 * @return long
	 * @throws Exception
	 */
	public static long getFolderSize(File f) throws Exception// 閸欐牕绶遍弬鍥︽婢剁懓銇囩亸锟�	
	{
		long size = 0;
		File flist[] = f.listFiles();
		for (int i = 0; i < flist.length; i++) {
			if (flist[i].isDirectory()) {
				size = size + getFolderSize(flist[i]);
			} else {
				size = size + flist[i].length();
			}
		}
		return size;
	}

	/**
	 * convert to file size description
	 * @param file size
	 * @return
	 */
	public static String formetFileSize(long fileS) {// 鏉烆剚宕查弬鍥︽婢堆冪毈
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "";
		if (fileS < 1024) {
			fileSizeString = df.format((double) fileS) + "B";
		} else if (fileS < 1048576) {
			fileSizeString = df.format((double) fileS / 1024) + "K";
		} else if (fileS < 1073741824) {
			fileSizeString = df.format((double) fileS / 1048576) + "M";
		} else {
			fileSizeString = df.format((double) fileS / 1073741824) + "G";
		}
		return fileSizeString;
	}

	/**
	 * Get file extension name
	 * 閺傚洣娆㈤幙宥勭稊 閼惧嘲褰囬弬鍥︽閹碘晛鐫嶉崥锟�	 * @param filename
	 * @return
	 */
	public static String getExtensionName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}


	/**
	 * Get file name no extension
	 * 閺傚洣娆㈤幙宥勭稊 閼惧嘲褰囨稉宥呯敨閹碘晛鐫嶉崥宥囨畱閺傚洣娆㈤崥锟�	 * @param filename
	 * @return
	 */
	public static String getFileNameNoEx(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length()))) {
				return filename.substring(0, dot);
			}
		}
		return filename;
	}
	
	/**
	 * 鐏忓棗鐡х粭锔胯閸愭瑥鍙嗛幐鍥х暰閺傚洣娆�瑜版挻瀵氱�姘辨畱閻栨儼鐭惧鍕厬閺傚洣娆㈡径閫涚瑝鐎涙ê婀弮璁圭礉娴兼碍娓舵径褔妾烘惔锕�箵閸掓稑缂撻敍灞间簰娣囨繆鐦夋穱婵嗙摠閹存劕濮涢敍锟�
	 * 
	 * @param res
	 *            閸樼喎鐡х粭锔胯
	 * @param filePath
	 *            閺傚洣娆㈢捄顖氱窞
	 * @return 閹存劕濮涢弽鍥唶
	 */
	public static boolean string2File(String res, String filePath) {
		boolean flag = true;
		BufferedReader bufferedReader = null;
		BufferedWriter bufferedWriter = null;
		try {
			File distFile = new File(filePath);
			if (!distFile.getParentFile().exists())
				distFile.getParentFile().mkdirs();
			bufferedReader = new BufferedReader(new StringReader(res));
			bufferedWriter = new BufferedWriter(new FileWriter(distFile));
			char buf[] = new char[1024]; // 鐎涙顑佺紓鎾冲暱閸栵拷
			int len;
			while ((len = bufferedReader.read(buf)) != -1) {
				bufferedWriter.write(buf, 0, len);
			}
			bufferedWriter.flush();
			bufferedReader.close();
			bufferedWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
			flag = false;
			return flag;
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return flag;
	}
    
	/**
	 * 閺傚洦婀伴弬鍥︽鏉烆剚宕叉稉鐑樺瘹鐎规氨绱惍浣烘畱鐎涙顑佹稉锟�	 * 
	 * @param file
	 *            閺傚洦婀伴弬鍥︽
	 * @param encoding
	 *            缂傛牜鐖滅猾璇茬�
	 * @return 鏉烆剚宕查崥搴ｆ畱鐎涙顑佹稉锟�	 * @throws IOException
	 */
	public static String file2String(File file, String encoding) {
		InputStreamReader reader = null;
		StringWriter writer = new StringWriter();
		try {
			if (encoding == null || "".equals(encoding.trim())) {
				reader = new InputStreamReader(new FileInputStream(file),
						encoding);
			} else {
				reader = new InputStreamReader(new FileInputStream(file));
			}
			// 鐏忓棜绶崗銉︾ウ閸愭瑥鍙嗘潏鎾冲毉濞达拷
			char[] buffer = new char[DEFAULT_BUFFER_SIZE];
			int n = 0;
			while (-1 != (n = reader.read(buffer))) {
				writer.write(buffer, 0, n);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (reader != null)
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		// 鏉╂柨娲栨潪顒佸床缂佹挻鐏�
		if (writer != null)
			return writer.toString();
		else
			return null;
	}
	
	
	public static void appendString(String fileName, String str) {
		// step 1
		File txtFile = new File(fileName);
		File tmpFile = new File(fileName + ".temp");
		try {

			if (txtFile.exists()) {

				txtFile.renameTo(tmpFile);

				// step 2 追加一条记录
				FileWriter fw = new FileWriter(tmpFile, true);
				fw.write(str + "\r\n");
				fw.close();

				// step 3
				tmpFile.renameTo(txtFile);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			//

		}

	}
}
